package cn.xuqiudong.rpc.protocol.http;

import org.apache.catalina.*;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.core.StandardEngine;
import org.apache.catalina.core.StandardHost;
import org.apache.catalina.startup.Tomcat;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * 描述: tomcat 服务端
 * @author Vic.xu
 * @date 2022-03-04 10:13
 */
public class XqdHttpServer {

    private Integer port;

    public XqdHttpServer(Integer port) {
        this.port = port;
    }

    /*
     *tomcat 结构  参照 server.xml
     *   - Server
     *   - -  Service
     *   - - - - Connector
     *   - - - - Engine
     *   - - - - - - Host
     *   - - - - - - - - Context
     *
     */

    /**
     * 启动tomcat
     * @throws UnknownHostException
     */
    public void start() throws UnknownHostException {
        String hostname = InetAddress.getLocalHost().getHostAddress();

        Tomcat tomcat = new Tomcat();
        Server server = tomcat.getServer();
        Service service = server.findService("Tomcat");

        Connector connector = new Connector();
        connector.setPort(port);

        Engine engine = new StandardEngine();
        engine.setDefaultHost(hostname);

        Host host = new StandardHost();
        host.setName(hostname);

        String contextPath = "";
        Context context = new StandardContext();
        context.setPath(contextPath);
        context.addLifecycleListener(new Tomcat.FixContextListener());

        host.addChild(context);
        engine.addChild(host);

        service.setContainer(engine);
        service.addConnector(connector);

        tomcat.addServlet(contextPath,"dispatcher", new XqdDispatcherServlet());
        context.addServletMappingDecoded("/*", "dispatcher");

        try {
            tomcat.start();
            tomcat.getServer().await();
        } catch (LifecycleException e) {
            e.printStackTrace();
        }


    }
}
